<!--
*  2021-03-15
*  样品详情
-->
<template>
  <div id="app" class="sample-edit">
    <!-- 头部导航 -->
    <van-nav-bar
      title="样品详情"
      ref="header"
      left-arrow
      left-text="返回"
      @click-left="onClickLeft"
    >
    </van-nav-bar>
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group>
        <van-cell title="产品编号">
          <template>
            <van-field
              v-model="printRow.no"
              placeholder="请输入"
              clearable
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="名称">
          <template>
            <van-field
              v-model="printRow.name"
              placeholder="请输入"
              clearable
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="颜色">
          <template>
            <van-field
              v-model="printRow.colorNo"
              placeholder="请输入"
              clearable
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="克重">
          <template>
            <van-field
              v-model="printRow.greyMiWeight"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="幅宽">
          <template>
            <van-field
              v-model="printRow.width"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="成份">
          <template>
            <van-field
              v-model="printRow.composition"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="经纱密度">
          <template>
            <van-field
              v-model="printRow.LonDensity"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="纬纱密度">
          <template>
            <van-field
              v-model="printRow.LatDensity"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="剪样布样">
          <template #right-icon>
            <van-switch v-model="checked" size="24" />
          </template>
        </van-cell>
        <van-cell
          title="生产日期"
          is-link
          :value="printRow.produceDate"
          @click="show = true"
        ></van-cell>
        <van-cell title="生产周期">
          <template>
            <van-field
              v-model="printRow.cycle"
              placeholder="请输入"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="染色分类">
          <template>
            <van-radio-group v-model="printRow.dyeType" direction="horizontal">
              <van-radio :name="1">匹染</van-radio>
              <van-radio :name="2">散染</van-radio>
            </van-radio-group>
          </template>
        </van-cell>
        <van-cell center title="是否有纱">
          <template #right-icon>
            <van-switch v-model="isYarned" size="24" />
          </template>
        </van-cell>
        <van-cell center title="是否有原料">
          <template #right-icon>
            <van-switch v-model="isMaterialed" size="24" />
          </template>
        </van-cell>

        <van-cell title="坯布数量">
          <template>
            <van-field
              v-model="printRow.greyNum"
              placeholder="坯布数量"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="成品数量">
          <template>
            <van-field
              v-model="printRow.clothNum"
              placeholder="成品数量"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>

        <van-cell title="起订数量">
          <template>
            <van-field
              v-model="printRow.orderNum"
              placeholder="起订数量"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="参考价格">
          <template>
            <van-field
              v-model="printRow.price"
              placeholder="起订数量"
              clearable
              type="tel"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="样品图片">
          <template>
            <van-uploader
              v-model="fileList"
              :max-count="1"
              :after-read="afterRead"
            />
          </template>
        </van-cell>
      </van-cell-group>
    </better-scroll>

    <van-cell-group class="sample-edit__btn">
      <van-button
        block
        type="info"
        class="bgColor"
        v-if="printRow.id == ''"
        @click="onClickConfirm"
        >提交</van-button
      >
      <van-button block type="info" class="bgColor" v-else @click="onClickPrint"
        >打印</van-button
      >
    </van-cell-group>

    <!-- 日期筛选 -->
    <van-calendar
      v-model="show"
      :min-date="minDate"
      :max-date="maxDate"
      :round="false"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import { openWin, deepCopy } from "@/utils/index";
import { getClothSampleStoreCheck, getByUploadKey } from "@/api/yarn";
import dayjs from "dayjs";
import { getMacAddress } from "@/utils/auth";

export default {
  name: "sampleEdit",
  data() {
    return {
      tableData: [],
      totalPage: 1,
      showPicker: false,
      printRow: {
        id: "",
        no: "",
        name: "",
        colorNo: "",
        greyMiWeight: "",
        produceDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        width: "",
        composition: "",
        LonDensity: 0,
        LatDensity: 0,
        greyNum: 0,
        clothNum: 0,
        cycle: "",
        orderNum: "",
        dyeType: 1,
        type: 1,
        yarnExists: 1,
        materialExists: 1,
        price: "",
        samplePic: "",
      },
      defaultFrom: {},
      printStatus: false,
      minDate: new Date(dayjs().subtract(1, "year")),
      maxDate: new Date(),
      show: false,
      isYarned: true,
      isMaterialed: true,
      checked: true,
      fileList: [],
      logo: require("./../../../assets/img/list.png"),
    };
  },
  watch: {
    // 原料
    isMaterialed() {
      this.printRow.materialExists = this.isMaterialed ? 1 : 0;
    },
    // 纱线
    isYarned() {
      this.printRow.yarnExists = this.isYarned ? 1 : 0;
    },
    // 剪样布样
    checked() {
      this.printRow.type = this.checked ? 1 : 2;
    },
  },
  created() {
    const that = this;
    that.defaultFrom = deepCopy(that.printRow);
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      that.fileList = [];
      if (JSON.stringify(window.api.pageParam) != "{}") {
        that.printRow = window.api.pageParam;
        if (that.printRow.samplePic) {
          getByUploadKey({
            type: "YWBY",
          }, (res) => {
            let url = process.env.VUE_APP_UPLOAD_URL + "/res/" + that.printRow.samplePic + "?accessToken=" + res.accessToken;
            that.fileList.push({
              name: that.printRow.samplePic,
              url: url,
            });
          });
        }
      } else {
        if (getMacAddress()) {
          that.isEnabledBluetooth();
        } else {
          that.$toast.fail('如需打印，请退出登录选择打印机')
        }
      }

      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回
    onClickLeft() {
      openWin("sample");
    },
    onConfirm(val) {
      this.printRow.produceDate = dayjs(val).format("YYYY-MM-DD HH:mm:ss");
    },
    // 上传图片
    afterRead(file) {
      const _this = this;
      _this.file = file.file;
      _this.printRow.samplePic = "";
      // file.status = "uploading";
      // file.message = "上传中...";
      getByUploadKey(
        {
          type: "YWBY",
        },
        (res) => {
          // 上传
          this.onGetByUploadServe(res.accessToken);
        }
      );
    },
    // 上传
    onGetByUploadServe(uploadKey) {
      const _this = this;
      let form = new FormData();
      form.append("files", this.file);
      let oReqCos = new XMLHttpRequest();
      oReqCos.open(
        "POST",
        process.env.VUE_APP_UPLOAD_URL + "/file_upload/upload"
      );
      oReqCos.setRequestHeader("x-yd-access-token", uploadKey);
      oReqCos.onload = function () {
        if (oReqCos.status === 200) {
          let res = JSON.parse(oReqCos.response);
          if (res.code === 2000) {
            // 上传成功
            _this.printRow.samplePic = res.data;
            _this.$toast.success("上传成功");
          } else {
            // 上传失败
            _this.$toast.fail("上传失败");
          }
        } else {
          // 上传失败
          _this.$toast.fail("上传失败");
        }
      };
      oReqCos.send(form);
    },
    // 保存
    onClickConfirm() {
      const that = this;
      getClothSampleStoreCheck(this.printRow, (res) => {
        that.printStatus = true;
        this.printRow.id = res;
        that.$toast({
          type: "success",
          message: "打印中",
          duration: 1000,
          onClose: () => {
            that.onClickPrint();
          },
        });
      });
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: getMacAddress() ? getMacAddress().address : '',
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.connectionStatus = true;
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    that.printLabel();
                  },
                });
              }
              if (status) {
                that.onClickAddStore();
              }
            } else if (ret.message === "连接失败") {
              that.connectionStatus = false;
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            } else {
              that.connectionStatus = false;
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              lineType: "image", //绘制图片
              x: 370,
              y: 10,
              data: that.logo, //支持fs:// widget://
            },

            {
              //绘制文本
              lineType: "text",
              x: 370,
              y: 130,
              rotation: 90,
              xscal: 1,
              yscal: 1.5,
              data: "领 先 工 ",
            },
            {
              //绘制文本
              lineType: "text",
              x: 380,
              y: 130 + 110,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: "艺 多 ",
            },
            {
              //绘制文本
              lineType: "text",
              x: 370,
              y: 130 + 180,
              rotation: 90,
              xscal: 1,
              yscal: 1.5,
              data: "创 奇 迹 ",
            },
            // 产品编号
            {
              //绘制文本
              lineType: "text",
              x: 300,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "产品编号",
            },
            {
              //绘制文本
              lineType: "text",
              x: 270,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "ITEM NO",
            },
            {
              //绘制文本
              lineType: "text",
              x: 295,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.no.substr(0, 10),
            },
            // 克重
            {
              //绘制文本
              lineType: "text",
              x: 220,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "克  重",
            },
            {
              //绘制文本
              lineType: "text",
              x: 190,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "WEIGHT",
            },
            {
              //绘制文本
              lineType: "text",
              x: 215,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.greyMiWeight + "g/m",
            },
            // 成份
            {
              //绘制文本
              lineType: "text",
              x: 140,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "成  份",
            },
            {
              //绘制文本
              lineType: "text",
              x: 110,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "content",
            },
            {
              //绘制文本
              lineType: "text",
              x: 135,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: that.printRow.composition,
            },
            // 名称
            {
              //绘制文本
              lineType: "text",
              x: 60,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "名称",
            },
            {
              //绘制文本
              lineType: "text",
              x: 30,
              y: 10,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "NAME",
            },
            {
              //绘制文本
              lineType: "text",
              x: 55,
              y: 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.name,
            },
            // 颜色/色号
            {
              //绘制文本
              lineType: "text",
              x: 300,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "颜色/色号",
            },
            {
              //绘制文本
              lineType: "text",
              x: 270,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "COLOR NO",
            },
            {
              //绘制文本
              lineType: "text",
              x: 295,
              y: 250 + 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.colorNo,
            },
            // 幅宽
            {
              //绘制文本
              lineType: "text",
              x: 220,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "幅 宽",
            },
            {
              //绘制文本
              lineType: "text",
              x: 190,
              y: 250,
              rotation: 90,
              xscal: 1,
              yscal: 1,
              data: "WIDTH",
            },
            {
              //绘制文本
              lineType: "text",
              x: 215,
              y: 250 + 120,
              rotation: 90,
              xscal: 1,
              yscal: 2,
              data: that.printRow.width + "cm",
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 10,
              y: 400,
              level: "L", //L|M|H|Q
              cellwith: 5,
              rotation: 0, // 0|90|180|270
              data: that.printRow.id,
            },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.printStatus = false;
            that.printRow = deepCopy(that.defaultFrom);
            that.$toast.success("打印成功");
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
    onClickPrint() {
      const that = this;
      if (!getMacAddress()) {
        this.$toast.fail("如需打印，请退出登录选择打印机");
        return false;
      }
      this.printStatus = true;
      this.$toast({
        type: "success",
        message: "打印中",
        duration: 1000,
        onClose: () => {
          that.getConnectState();
        },
      });
    },
  },
};
</script>

<style lang="scss">
.sample-edit {
  height: 100%;
  .public-scroll {
    height: calc(100vh - 147px);
    overflow: hidden;
    .van-cell__value {
      overflow: initial !important;
      .van-cell {
        padding: 0;
        .van-field__control {
          text-align: right;
        }
      }
      .van-radio-group {
        display: flex;
        justify-content: flex-end;
      }
    }
    .van-switch__node {
      width: 20px !important;
      height: 20px !important;
    }
  }
  .sample-edit__btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>
